﻿package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class MultiSpring extends Sprite
	{
		private var ball:Ball;
		
		public var bar:Bar;
		public var barX:Number;
		public var barY:Number;
		public var barRot:Number;
		public var barLength:Number;
		public var barHeight:Number;
		
		public var point:Ball; //The fixed point
		
		private var spring:Number;
		private var friction:Number;
		private var springLength:Number;
				
		public function MultiSpring()
		{
			spring = 0.1;
			friction = 0.8;
			springLength = 50;
			
			barX = 100;
			barY = 300;			
			barRot = 0;
			barLength = 300;
			barHeight = 5;
			
			init();
		}
		
		private function init():void
		{
			//ball = new Ball(20);
			//ball.x = 400;
			//ball.y = 150;
			//ball.addEventListener(MouseEvent.MOUSE_DOWN, onpress);
			//addChild(ball);
			
			bar = new Bar(barX, barY, barRot);
			bar.x = barX;
			bar.y = barY;
			addChild(bar);
			
			point = new Ball(10, 0x0000ff);			
			point.x = 400;
			point.y = 400;			
			addChild(point);		
			
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			//addEventListener(MouseEvent.MOUSE_UP, onrelease);
		}
		
		private function onEnterFrame(event:Event):void
		{				
			springTo(bar, point);
			
			graphics.clear();
			graphics.lineStyle(1);
			
			graphics.moveTo(bar.x + barLength, bar.y + barHeight);
			graphics.lineTo(point.x, point.y);			
		}
		
		private function springTo(bar:Bar, point:Ball):void
		{
			var springPointX = bar.x + barLength;
			var springPointY = bar.y + barHeight;
			
			var dx:Number = point.x - springPointX;
			var dy:Number = point.y - springPointY;
			var angle:Number = Math.atan2(dy, dx);
			var targetX:Number = point.x - Math.cos(angle) * springLength;
			var targetY:Number = point.y - Math.sin(angle) * springLength;
			bar.vx += (targetX - springPointX) * spring;
			bar.vy += (targetY - springPointY) * spring;
			bar.vx *= friction;
			bar.vy *= friction;
			bar.x += bar.vx;
			bar.y += bar.vy;
		}
		
		private function onpress(event:MouseEvent):void
		{
			event.target.startDrag();
		}
		
		private function onrelease(event:MouseEvent):void
		{
			event.target.stopDrag();
		}
	}
}
